// pages/villager/villager.js
const app = getApp()
const villagersData = require('../../utils/villagers.js').villagers;

Page({
  data: {
    name: "未知",
    species: "未知",
    personality: "未知",
    birthday: "未知",
    gender: "未知",
    phrase: "未知",
    imagePath: "/images/icon_encyclopedia.png", // 默认图片路径
    loading: true,
    error: false
  },

  onLoad(options) {
    const name = options.name || options.id;
    
    // 数据校验：确保name为有效值
    if (!name) {
        console.error('无效的name参数:', name);
        this.setData({
            error: true,
            loading: false
        });
        return;
    }
    
    // 显示加载状态
    this.setData({
      loading: true,
      error: false
    });

    // 从本地数据获取小动物数据
    this.fetchVillagerData(name);
  },

  fetchVillagerData(villagerName) {
    try {
        // 在本地数据中查找匹配的小动物
        const villager = villagersData.find(item => item['名称'] === villagerName);
        
        if (villager) {
            // 性别字段适配：'♂'->'男'，'♀'->'女'
            var gender = villager['性别'] === '♂' ? '男' : (villager['性别'] === '♀' ? '女' : '未知');
            // 性格字段适配：去除血型后缀
            var personality = villager['性格'] ? villager['性格'].replace(/[AB型]/g, '') : '未知';
          
            // 使用已有的本地路径字段，并修复可能的重复前缀问题
            var imagePath = villager['本地路径'] || "/images/icon_encyclopedia.png";
            // 修复重复的云存储前缀
            if (imagePath.startsWith('cloud://') && imagePath.includes('cloud://', 8)) {
              // 如果路径包含重复的cloud://前缀，则去除第一个前缀
              imagePath = imagePath.substring(imagePath.indexOf('cloud://', 8));
            }
          
            // 数据校验
            var name = villager['名称'] || "未知";
            var species = villager['种族'] || "未知";
            var birthday = villager['生日'] || "未知";
            var phrase = villager['初始口头禅'] || "未知";
          
            this.setData({
                name: name,
                species: species,
                personality: personality,
                birthday: birthday,
                gender: gender,
                phrase: phrase,
                imagePath: imagePath, // 使用修复后的图片路径
                loading: false
            });
        } else {
            this.setData({
                error: true,
                loading: false
            });
            console.log('未找到小动物数据，查询名称:', villagerName);
        }
    } catch (err) {
        console.error('获取小动物数据失败:', err);
        this.setData({
            error: true,
            loading: false
        });
    }
  },

  onImageError(e) {
    console.error('图片加载失败:', e);
    // 图片加载失败时使用默认图片
    this.setData({
      imagePath: "/images/icon_encyclopedia.png"
    });
  },
  
  onRetry() {
    const name = this.options.name || this.options.id;
    this.setData({
      loading: true,
      error: false
    });
    this.fetchVillagerData(name);
  }
})